<?php

/**
 * login actions.
 *
 * @package    MaxJobs
 * @subpackage login
 * @author     Micheal Mouner
 * @version    SVN: $_id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class loginActions extends MaxActions
{

    /**
     * Login action
     * @param sfWebRequest $request 
     * @author Mina Gerges
     */
    public function executeLogin(sfWebRequest $request)
    {
        $redirectUrl = $this->generateUrl('HomePage');
        if ($this->getUser()->isAuthenticated())
        {
            $this->redirect($redirectUrl);
        }
        $this->loginForm = new LoginForm(null, array('i18n' => $this->i18n));
        if ($request->isMethod(sfWebRequest::POST))
        {
            $this->loginForm->bind($request->getParameter($this->loginForm->getName()));
            if ($this->loginForm->isValid())
            {
                // fro rember me
                if ($request->getParameter('remember'))
                {
                    $random   = md5(time() * rand(2, 2000000000));
                    $settings = $this->loginForm->getSettingsObject();
                    $settings->setRememberMeCode($random);
                    $settings->save();
                    // add cookie named in the browser
                    sfContext::getInstance()->getResponse()->setCookie(sfConfig::get('app_cookie_name'), $random, time() + 60 * 60 * 24 * 365, '/');
                }
                $user     = $this->loginForm->getUserObject();
                // Add credential
                if ($user->getRole()->getType() == Role::CONTROLLER)
                {
                    $this->getUser()->addCredential('admin');
                    if (!$user->getRole()->getEditable())
                    {
                        $this->getUser()->addCredential('superAdmin');
                    }
                }
                // create MaxUser object
                $maxUserObject = new MaxUser($user);
                $this->getUser()->setAttribute('MaxUser', $maxUserObject);
                $this->getUser()->setAuthenticated(true);
                if ($request->getPostParameter('url') && $request->getPostParameter('url') != $this->generateUrl('Login', array(), true))
                {
                    $redirectUrl = $request->getPostParameter('url');
                }
                $this->redirect($redirectUrl);
            }
            else
            {
                // error in login
                $this->getUser()->setFlash('message_failed', $this->i18n->__('Error in login data'));
            }
        }
    }

    /**
     * logout action 
     * @author Mina Gerges
     */
    public function executeLogout()
    {
        // clear all session opened for this user
        $this->getUser()->getAttributeHolder()->clear();
        sfContext::getInstance()->getUser()->setAuthenticated(false);

        // remove cookie
        sfContext::getInstance()->getResponse()->setCookie(sfConfig::get('app_cookie_name'), '', time() - 60, '/');

        // redirect to login page
        $this->redirect('Login');
    }

    /**
     * forgetPassword .. send email to user include link to add new password
     * @param sfWebRequest $request 
     * @author Mina Gerges
     */
    public function executeRequestNewPassword(sfWebRequest $request)
    {
        //validate existence
        if ($request->getMethod() == 'POST')
        {
            $username = $request->getParameter('uname');
            $user     = new User;
            $user     = UserTable::getInstance()->findOneByUsername($username);
            if (!$user)
            {
                $user = UserTable::getInstance()->findOneByEmail($username);
            }
            if ($user)
            {
                $token             = md5(rand(555, 888888888888888888));
                $user->setPasswordRequestToken($token);
                $user->save();
                // send mail to the user by the reset link
                $retunPasswordLink = $this->generateUrl('SetNewPassword', array('token'  => $token), true);
                $message = $this->getMailer()->compose(
                        array('nadeen@softxpert.com' => $this->i18n->__('new password')), $user->getEmail(), 'forget password link', <<<EOF
Yto return your password go to link {$retunPasswordLink}
EOF
                );
                $this->getMailer()->send($message);
                $this->getUser()->setFlash('message_success', 'URL of change password sent to your email');
            }
            else
            {
                $this->getUser()->setFlash('message_failed', 'username is not exist');
            }
        }
        return sfView::NONE;
    }

    /**
     * action for reset password from the link which send from executeForgetPassword action
     * @param sfWebRequest $request 
     */
    public function executeSetNewPassword(sfWebRequest $request)
    {
        $token = $request->getParameter('token');
        $user  = UserTable::getInstance()->findOneByPasswordRequestToken($token);
        // validate the token
        $this->forward404Unless($user);
        $this->form = new NewForgtPasswordForm($user, array('i18n' => $this->i18n));

        $this->done = false; // flag for dsiplay form or not
        if ($request->getMethod() == 'POST')
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                $this->form->getObject()->setPasswordRequestToken(null);
                $this->form->save();
                $this->done = true;
                $this->getUser()->setFlash('message_success', 'your password updated successfuly, now you can login with new password');
            }
        }
    }

//
//    /**
//     * @author Micheal Mouner
//     * @method login by (username or email) and password
//     * @param sfWebRequest $request 
//     */
//    public function executeLogin(sfWebRequest $request)
//    {
//        //ajax request after session terminated redirect to login page
//        if ($request->isXmlHttpRequest())
//        {
//            $this->getResponse()->setContent('notLogin');
//            return sfView::NONE;
//        }
//        // if user authenticated redirect to home page
//        if ($this->getUser()->isAuthenticated())
//        {
//            $this->redirect('@HomePage');
//        }
//        /*
//         * get ip and check in DB this ip
//         * check he/she is a valid user or suspecious one
//         */
//        $suspiciousUser = SuspiciousLoginTable::getInstance()->findOneBy('ip_address', $request->getRemoteAddress());
//        $this->numberOfLoginTyries = $suspiciousUser['count'];
//        // less than 5 tries no captcha in the form
//        if ($suspiciousUser['count'] <= 4)
//        {
//            $this->form = new loginForm(null, array('captcha' => false));
//        }
//        else
//        {
//            $this->form = new loginForm(null, array('captcha' => true));
//        }
//
//        if ($request->getMethod() == 'POST')
//        {
//            $loginData = $request->getParameter('login', false);
//            $this->form->bind($loginData);
//            if ($this->form->isValid())
//            {
//                /*
//                 * function to prepare for the login if username and pass is correct
//                 * add number of login tries to the data send to function
//                 */
//                $loginData['numberOfLoginTries'] = $suspiciousUser['count'];
//                if ($this->prepareUserToLogin($loginData, $request))
//                {
//                    //redirect to the page that the user come from
//                    $uri = $request->getPostParameter('url');
//                    //redirect to home page
//                    if ($uri == $this->getController()->genUrl('@Login'))
//                    {
//                        $this->redirect('/');
//                    }
//                    else
//                    {
//                        $this->redirect($uri);
//                    }
//                }
//            }
//            else
//            {
//                // set error message
//                $this->getUser()->setFlash('message', $this->getContext()->getI18N()->__('Wrong Username Or Password'));
//                //add record by ip_address
//                $this->insertSuspeciousLogin($request->getRemoteAddress(), $suspiciousUser['count']);
//            }
//            /*
//             * add captcha to the form before render it to the user 
//             * after 5 tries
//             */
//            if ($suspiciousUser['count'] == 4)
//            {
//                $this->form = new loginForm(null, array('captcha' => true));
//            }
//        }
//    }
//
//    /**
//     * @author Micheal Mouner
//     * @method remove all sessions
//     * @param sfWebRequest $request 
//     */
//    public function executeLogout(sfWebRequest $request)
//    {
//        // clear all session opened for this user
//        $this->getUser()->getAttributeHolder()->clear();
//        // remove cookie
//        sfContext::getInstance()->getResponse()->setCookie('MaxJobs', '', time() - 3600, '/');
//        // not authenticated
//        sfContext::getInstance()->getUser()->setAuthenticated(false);
//        // redirect to login page
//        $this->redirect('@Login');
//    }
//
//    public function executeRequestNewPassword(sfWebRequest $request)
//    {
//        $this->forward404Unless($request->isXmlHttpRequest());
//        $uname = $request->getParameter('uname');
//        $user  = UserTable::getInstance()->findOneByUsername($uname);
//        if ($user)
//        {
//            $user->setPasswordRequest(true);
//            $user->setPasswordRequestToken(md5(rand(1, 20000) * time()));
//            $user->setPasswordRequestEndDate(date('Y-m-d h:i:s', time() + 12 * 60 * 60));
//            $user->save();
//            // send mail to user
//
//            $returnMsg = $this->i18n->__('change password Url sended to your email');
//        }
//        else
//        {
//            $returnMsg = $this->i18n->__('username is not exist');
//        }
//        return $this->renderJson(array('msg' => $returnMsg));
//    }
//
//    public function executeSetNewPassword()
//    {
//        
//    }
//
//    /**
//     * @method forgetPassword .. send email to yser include link to add new password
//     * @author Micheal Mouner
//     * @param sfWebRequest $request 
//     */
//    public function executeForgetPassword(sfWebRequest $request)
//    {
//        $this->form = new forgetpasswordForm(null, array('slug' => $this->getUser()->getAttribute('companySlug')));
//        //validate existence
//        if ($request->getMethod() == 'POST')
//        {
//            $forget = $request->getParameter('forget');
//            $this->form->bind($forget);
//            $this->validData = false;
//            if ($this->form->isValid())
//            {
//                if (UserTable::getInstance()->requestChangePassword($user['username']))
//                {
//                    // send mail to the user by the reset link
//
//                    return $this->renderText(true);
//                }
//            }
//        }
//        else
//        {
//            //$this->forward404();
//        }
////        return $this->renderPartial('forgetPassword');
//    }
//
//    /**
//     * @author Micheal Mouner
//     * @method enter the new password after send mail
//     * @param sfWebRequest $request 
//     */
//    public function executeNewPassword(sfWebRequest $request)
//    {
//        $companySlug = $this->getUser()->getAttribute('companySlug');
//        $token       = $request->getParameter('token');
//        $user        = UserTable::getInstance()->getUserByRequestPasswordToken($token, $companySlug);
//        if (isset($user['password_request']) && $user['password_request'] == 1 && $user['password_request_end_date'] >= date('Y-m-d h:i:s', time()))
//        {
//            $this->form = new newpasswordForm();
//            if ($request->getMethod() == 'POST')
//            {
//                $new = $request->getParameter('new');
//                $this->form->bind($new);
//                if ($this->form->isValid())
//                {
//                    UserTable::getInstance()->resetPassword($user['username'], $new['password'], $user['token']);
//                    $this->form = new loginForm();
//                    $this->getUser()->getAttributeHolder()->clear();
//                    sfContext::getInstance()->getResponse()->setCookie('MaxJobs', '', time() - 3600, '/');
//                    sfContext::getInstance()->getUser()->setAuthenticated(false);
//                    $this->redirect('@Login');
//                }
//            }
//        }
//        else
//        {
//            $this->forward404($this->getContext()->getI18N()->__('This Request Was Expired -- Create New One'));
//        }
//    }
//
//    /**
//     * @author Micheal Mouner
//     * @method for testing
//     * @param sfWebRequest $request 
//     */
//    public function executeDone(sfWebRequest $request)
//    {
//
//        echo $request->getCookie('MaxJobs');
//        echo 'user:<pre>';
//        print_r($this->getContext()->getUser()->getAttribute('user'));
//        echo '</pre>';
//
//        echo 'company:<pre>';
//        print_r($this->getUser()->getAttribute('company'));
//        echo '</pre>';
//    }
//
//    /**
//     * @author Micheal Mouner
//     * @method change password if u know your old password
//     * @param sfWebRequest $request 
//     */
//    public function executeChangePassword(sfWebRequest $request)
//    {
//        $userSession = $this->getUser()->getAttribute('user');
//        $this->_username = $userSession['username'];
//        $user        = UserTable::getInstance()->findOneById($userSession['id']);
//        $this->form = new ChangePasswordForm(array(), array('user' => $user));
//        if ($request->getMethod() == 'POST')
//        {
//            $reset = $request->getParameter('reset');
//            $this->form->bind($reset);
//            if ($this->form->isValid())
//            {
//                if (User::encrypt($reset['password3'], $user['twitter']) == $user->getPassword())
//                {
//                    UserTable::getInstance()->changePassword($user['username'], User::encrypt($reset['password'], $user['twitter']));
//                    $this->redirect('@Logout');
//                }
//                else
//                {
//                    $this->getUser()->setFlash('message', $this->getContext()->getI18N()->__('Wrong Old Password !'));
//                }
//            }
//        }
//    }
//
//    /**
//     * @author Micheal Mouner
//     * @method insert record in DB of login attack
//     * @param type $request 
//     */
//    protected function insertSuspeciousLogin($ip, $count)
//    {
//        $count++;
//        if ($count == 1)
//        {
//            //save ip here for first time
//            SuspiciousLoginTable::getInstance()->insertSuspiciousPerson($ip);
//        }
//        else
//        {
//            //update counter of number of login error tries
//            SuspiciousLoginTable::getInstance()->updateErrorInLoginCount($ip, $count);
//        }
//    }
//
//    /**
//     * check if the user authenticated or not
//     * add vidsUser in the session with company info and user info
//     * user roles and camera roles in the vidsUser object
//     * @author Micheal Mouner
//     * @param mixed $loginData
//     * @param sfWebRequest $request
//     * @return boolean
//     */
//    protected function prepareUserToLogin($loginData, $request)
//    {
//
//        $user = UserTable::getInstance()->checkForLogin($loginData['username'], $loginData['password']);
//        //check user exist in database
//        if ($user)
//        {
//            //checkbox is marked to remmember
//            if ($request->getParameter('remmember'))
//            {
//                // fro rember me
//                $random = md5(time() * rand(2, 2000000000)) . 'fa' . rand(1, 87548986541265487);
//                $user->setRememberMeCode($random);
//                $user->save();
//                // add cookie named in the browser
//                sfContext::getInstance()->getResponse()->setCookie(sfConfig::get('app_cookie_name'), $random, time() + 60 * 60 * 24 * 365, '/');
//            }
//            // authenticated user
//            $this->getUser()->setAuthenticated(true);
//
//            /*
//             * Add credential
//             * by Mina.gerges
//             */
//
//            if ($user->getRole()->getType() == Role::CONTROLLER)
//            {
//                $this->getUser()->addCredential('admin');
//                if (!$user->getRole()->getEditable())
//                {
//                    $this->getUser()->addCredential('superAdmin');
//                }
//            }
//            // create MaxUser object
//            $maxUserObject = new MaxUser($user);
//            $this->getUser()->setAttribute('MaxUser', $maxUserObject);
//            /*
//             * end - Add credential-
//             */
//            //remove from suspecious after true login
//            SuspiciousLoginTable::getInstance()->deleteAfterTrueLogin($request->getRemoteAddress());
//            // change last login
//            UserTable::getInstance()->changeLastLogin($user['id']);
//            return true;
//        }
//        else
//        {
//            // set error message
//            $this->getUser()->setFlash('message', $this->getContext()->getI18N()->__('Wrong Username Or Password'));
//        }
//        // insert suspecious login try in the table
//        $this->insertSuspeciousLogin($request->getRemoteAddress(), $loginData['numberOfLoginTries']);
//        return false;
//    }
}

